package net.dopan.pigframe.user.controller;

import com.google.code.kaptcha.Producer;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.dopan.pigframe.core.base.controller.response.ResponseBean;
import net.dopan.pigframe.core.utils.Assert;
import net.dopan.pigframe.core.utils.SecurityConstants;
import net.dopan.pigframe.user.service.SysUserService;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;

/**
 * @Package: net.dopan.pigframe.user.controller
 * @Title: ValidateCodeController
 * @Description: 验证码提供
 * @author: 刘宽
 * @date: 2018/9/2 21:21
 */
@Controller
@Api(tags = "验证码提供接口(API)", description = "验证码提供相关操作")
public class ValidateCodeController {

    @Autowired
    private Producer producer;

    @Autowired
    private SysUserService userService;

    /**
     * 创建验证码
     *
     * @param request request
     * @throws Exception
     */
    @GetMapping(SecurityConstants.DEFAULT_VALIDATE_CODE_URL_PREFIX + "/{randomStr}")
    @ApiOperation(value = "创建验证码", notes = "创建验证码")
    public void createCode(@PathVariable String randomStr, HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        Assert.isBlank(randomStr, "机器码不能为空");
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");
        //生成文字验证码
        String text = producer.createText();
        //生成图片验证码
        BufferedImage image = producer.createImage(text);
        userService.saveImageCode(randomStr, text);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "JPEG", out);
        IOUtils.closeQuietly(out);
    }

    /**
     * 发送手机验证码
     * 后期要加接口限制
     *
     * @param mobile 手机号
     * @return R
     */
    @ResponseBody
    @GetMapping(SecurityConstants.MOBILE_VALIDATE_CODE_URL_PREFIX + "/{mobile}")
    @ApiOperation(value = "发送手机验证码", notes = "发送手机验证码")
    public ResponseBean<Boolean> createCode(@PathVariable String mobile) {
        Assert.isBlank(mobile, "手机号不能为空");
        return userService.sendSmsCode(mobile);
    }
}
